package com.rongshu.view.home.fragment.dialog;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rongshu.R;
import com.rongshu.eventbus.CleanKeyBoard;
import com.rongshu.eventbus.UpdateCommmentCount;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.home.activity.SearchAtUserActivity;
import com.rongshu.view.home.adapter.ArticleCommentAdapter;
import com.rongshu.view.home.contract.ArticleCommentView;
import com.rongshu.view.home.entity.ArticleItem;
import com.rongshu.view.home.entity.CommentDetails;
import com.rongshu.view.home.entity.CommentReplysBean;
import com.rongshu.view.home.entity.ContentClass;
import com.rongshu.view.home.listener.EndlessRecyclerOnScrollListener;
import com.rongshu.view.home.listener.OnCommentItemFunctionClickListener;
import com.rongshu.view.home.presenter.ArticleCommentPresenter;
import com.rongshu.view.userInfo.activity.PersonDetailsActivity;
import com.rongshu.widget.BanyanDialog;
import com.rongshu.widget.popup.EasyPopup;
import com.rongshu.widget.popup.XGravity;
import com.rongshu.widget.popup.YGravity;
import com.trello.rxlifecycle.LifecycleTransformer;
import com.utils.DensityUtil;
import com.utils.FastClickUtils;
import com.widget.titlebar.ImmersionBar;
import com.widget.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * created by zhengweis on 2019/7/10.
 * description：底部弹窗的评论窗口
 */
public class ArticleCommentDialog extends BottomSheetDialogFragment implements OnCommentItemFunctionClickListener, ArticleCommentView {
    @BindView(R.id.edt_chat_input)
    EditText edtChatInput;
    @BindView(R.id.iv_at)
    ImageView ivAt;
    @BindView(R.id.rv_comment)
    RecyclerView rvComment;
    @BindView(R.id.view_stub_empty)
    ViewStub viewStub;
    protected View inflate;
    protected RelativeLayout layoutEmpty;
    private InputCommentDialog inputCommentDialog;
    //点击的文章bean
    private ArticleItem articleItem;
    private Window win;
    //P
    ArticleCommentPresenter presenter;
    //评论的数据集合
    private List<CommentDetails.ResponseBean> mCommentDetails = null;
    //adapter
    private ArticleCommentAdapter mCommentAdapter = null;
    //分页加载
    private int pageIndex = 1;
    private int pageSize = 10;
    //是否还有下一页
    private boolean hasNext = true;
    //评论
    private int comment_id = 0, reply_id = 0;
    //删除评论回复的position
    private int replyPosition = 0;
    private int reply_pageIndex = 1;
    private int reply_pageSize = 100;
    //评论点赞position
    private int likePosition = 0;

    //local_position 局部刷新position
    private int local_position;
    //是否删除为回复
    private boolean isDeteleReply = false;
    //评论
    //@的用戶信息
    private LinkedHashMap<String, AuthorDetailBean> atMap = null;
    //request
    public static final int REQUEST_AT_USER = 0x01;
    //评论
    //正则
    private String REGEX = "@[\\u4e00-\\u9fa5\\w….-]+ ";
    private Pattern pattern = null;
    private Matcher matcher = null;
    //map
    private Map<String, Object> map = null;
    private Dialog dialog;

    public static ArticleCommentDialog getInstance(ArticleItem articleItem) {
        ArticleCommentDialog dialog = new ArticleCommentDialog();
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constant.INTENT_DATA, articleItem);
        dialog.setArguments(bundle);
        return dialog;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //给dialog设置主题为透明背景 不然会有默认的白色背景
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.custom_dialog2);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        dialog = super.onCreateDialog(savedInstanceState);
        //设置点击外部可消失
        dialog.setCanceledOnTouchOutside(true);
        win = dialog.getWindow();
        //这里设置dialog的进出动画
        win.setWindowAnimations(R.style.picker_view_slide_anim);
        ImmersionBar.with(this, dialog).keyboardEnable(false,
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
                .init();
        return dialog;
    }

    @Override
    public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 在这里将view的高度设置为精确高度，即可屏蔽向上滑动不占全屏的手势。
        //如果不设置高度的话 会默认向上滑动时dialog覆盖全屏
        View view = inflater.inflate(R.layout.fragment_article_comment_list, container, false);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                DensityUtil.getScreenHeight(getActivity()) / 10 * 7));
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@Nullable View view, @Nullable Bundle savedInstanceState) {
        articleItem = (ArticleItem) getArguments().getSerializable(Constant.INTENT_DATA);
        final int article_id = articleItem.getContribute_id();
        edtChatInput.setClickable(false);
        edtChatInput.setCursorVisible(false);
        edtChatInput.setFocusableInTouchMode(false);
        //评论
        mCommentDetails = new ArrayList<>();
        mCommentAdapter = new ArticleCommentAdapter(getActivity());
        mCommentAdapter.setResponseBeanList(mCommentDetails);
        mCommentAdapter.setOnItemFunctionClickListener(this);
        mCommentAdapter.setHasStableIds(true);
        //recyclerView
        LinearLayoutManager manager2 = new LinearLayoutManager(getActivity());
        rvComment.setLayoutManager(manager2);
        rvComment.setAdapter(mCommentAdapter);
        getPresenter().getCommentDetail(article_id, pageIndex, pageSize);
        rvComment.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                if (hasNext) {
                    mCommentAdapter.setLoadState(mCommentAdapter.LOADING);
                    pageIndex++;
                    getPresenter().getCommentDetail(article_id, pageIndex, pageSize);
                }
            }
        });
    }

    void titleTextChanged(String content) {
        //正则
        pattern = Pattern.compile(REGEX);
        matcher = pattern.matcher(content);
        SpannableString spannableString = new SpannableString(content);
        while (matcher.find()) {
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(getActivity(), R.color.color_3cc051));
            spannableString.setSpan(colorSpan, matcher.start(), matcher.end(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }
        edtChatInput.setText(spannableString);
    }

    @Override
    public void onStart() {
        super.onStart();
        BottomSheetDialog dialog = (BottomSheetDialog) getDialog();
        FrameLayout bottomSheet = dialog.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet);
        if (bottomSheet != null) {
            CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) bottomSheet.getLayoutParams();
            layoutParams.height = DensityUtil.getScreenHeight(getActivity()) / 10 * 7;
            BottomSheetBehavior<FrameLayout> behavior = BottomSheetBehavior.from(bottomSheet); // 初始为展开状态
            behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        ImmersionBar.with(this).destroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_AT_USER) {
                AuthorDetailBean authorDetailBean = (AuthorDetailBean) data.getSerializableExtra(Constant.INTENT_DATA);
                InputCommentDialog inputDialog = getInputDialog();
                inputDialog.updateInputContent(authorDetailBean, comment_id, reply_id);
                inputDialog.show(getChildFragmentManager(), InputCommentDialog.class.getSimpleName());
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dismissDialog();
    }

    @OnClick({R.id.edt_chat_input, R.id.iv_at, R.id.txt_send})
    public void onViewClicked(View view) {
        if (UserInfoUtils.getUserInfo() == null) {
            LoginUtils.toLogin(getActivity());
            return;
        }
        switch (view.getId()) {
            case R.id.edt_chat_input:
                getInputDialog().show(getChildFragmentManager(), InputCommentDialog.class.getSimpleName());
                break;
            case R.id.iv_at:
                Intent intent = new Intent(getActivity(), SearchAtUserActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, REQUEST_AT_USER);
                break;
            case R.id.txt_send:
                if (!FastClickUtils.isFastClick()) {
                    String content = edtChatInput.getText().toString();
                    if (TextUtils.isEmpty(content)) {
                        ToastUtils.show("输入信息不能为空");
                    } else {
                        if (articleItem != null) {
                            content = Uri.encode(content, "utf-8");
                            //发送评论
                            postCommentOrReplyAdd(comment_id, reply_id, content);
                        } else {
                            ToastUtils.show("文章未获取到");
                        }
                    }
                }
                break;
        }
    }

    private ArticleCommentPresenter getPresenter() {
        if (presenter == null) {
            presenter = new ArticleCommentPresenter(getActivity());
            presenter.attachView(this);
        }
        return presenter;
    }

    /**
     * 显示输入框弹窗
     */
    private InputCommentDialog getInputDialog() {
        //防止从其他页面返回时，dialog动画重复执行
        win.setWindowAnimations(0);
        if (inputCommentDialog == null) {
            inputCommentDialog = InputCommentDialog.getInstance(articleItem);
            inputCommentDialog.setDimissListener(new InputCommentDialog.OnDialoglistener() {
                @Override
                public void sendCommentSuccess(ResponseBody body) {
                    onPostCommentOrReplyAdd(body);
                }

                @Override
                public void onDismiss(String msg, LinkedHashMap<String, AuthorDetailBean> authorDetailBeanMap) {
                    //恢复dialog动画
                    win.setWindowAnimations(R.style.picker_view_slide_anim);
                    atMap = authorDetailBeanMap;
                    titleTextChanged(msg);
                }
            });
        }
        return inputCommentDialog;
    }

    /**
     * 文章评论/评论回复/回复回复
     */
    private void postCommentOrReplyAdd(int comment_id, int reply_id, String content) {
        map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("contribute_id", articleItem.getContribute_id());
        map.put("comment_id", comment_id);
        map.put("reply_id", reply_id);
        ContentClass contentClass = new ContentClass();
        contentClass.setContents(content);
        contentClass.setTitle(null);
        StringBuilder aiteStrsb = new StringBuilder();
        for (Map.Entry<String, AuthorDetailBean> entry : atMap.entrySet()) {
            if (!TextUtils.isEmpty(aiteStrsb)) {
                aiteStrsb.append(",");
            }
            aiteStrsb.append(entry.getValue().getUser_id_to());
        }
        contentClass.setAiteStr(aiteStrsb.toString());
        contentClass.setPenpalwill_id(null);
        getPresenter().postCommentOrReplyAdd((int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("comment_id"),
                (int) map.get("reply_id"),
                Common.encryptionSign(map),
                contentClass);
        map.clear();
    }

    /**
     * 接口返回评论列表
     */
    @Override
    public void onCommentMsg(List<CommentDetails.ResponseBean> responseBeanList) {
        if (responseBeanList != null) {
            mCommentDetails.addAll(responseBeanList);
            mCommentAdapter.notifyDataSetChanged();
            mCommentAdapter.setLoadState(mCommentAdapter.LOADING_COMPLETE);
            if (responseBeanList.size() < pageSize) {//请求不到数据，证明没有更多了
                hasNext = false;
                mCommentAdapter.setLoadState(mCommentAdapter.LOADING_END);
            }
            if (mCommentDetails.size() == 0) {//判断显示缺省页面
                mCommentAdapter.setLoadState(mCommentAdapter.LOADING_EMPTY);
                showEmptyLayout();
            } else {
                hideEmptyLayout();
            }
        }
    }

    @Override
    public void onOnecommentDetail(List<CommentReplysBean> commentReplysBeans) {
        mCommentAdapter.getResponseBeanList().get(local_position).setComment_replys(commentReplysBeans);
        mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
    }

    @Override
    public void onCommentOrReplyDelete(INetBean bean) {
        if (bean.getErrCode() == 0) {
            if (mCommentAdapter == null) {
                return;
            }
            List<CommentDetails.ResponseBean> responseBeans = mCommentAdapter.getResponseBeanList();
            if (isDeteleReply) {//回复评论
                CommentDetails.ResponseBean response = responseBeans.get(local_position);
                List<CommentReplysBean> replysBeans = response.getComment_replys();
                replysBeans.remove(replyPosition);
                int comment_replyCount = response.getComment_replyCount();
                if (comment_replyCount > 0) {
                    comment_replyCount = comment_replyCount - 1;
                    response.setComment_replyCount(comment_replyCount);
                }
                //如果此时集合中数据和comment_replyCount数据不一致，说明二者数据不一致，需要重新请求
                int replyCount = replysBeans.size();
                if (replyCount < comment_replyCount) {
                    mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                    //(此处问题在于，如果获取不到数据，当前一条没有更新view)
                    getPresenter().getOnecommentDetail(comment_id, reply_pageIndex, reply_pageSize);
                } else {
                    mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                }
            } else {//回复文章
                responseBeans.remove(local_position);
                mCommentAdapter.notifyItemRemoved(local_position);
                mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                EventBus.getDefault().post(new UpdateCommmentCount(false));
            }
            int itemCount = mCommentAdapter.getItemCount();
            if (itemCount == 0) {
                pageIndex = 1;
                getPresenter().getCommentDetail(articleItem.getContribute_id(), pageIndex, pageSize);
            }
            ToastUtils.show("删除成功");
        } else {
            ToastUtils.show("删除失败");
        }
        //清空标识
        cleanIdentifying();
    }

    @Override
    public void onCommentlike(INetBean iNetBean) {
        if (iNetBean.getErrCode() == 0) {
            if (iNetBean.getErrMsg().equals("评论点赞成功")) {
                if (mCommentAdapter != null) {
                    List<CommentDetails.ResponseBean> responseBeanList = mCommentAdapter.getResponseBeanList();
                    if (responseBeanList != null) {
                        int likeCount = responseBeanList.get(likePosition).getLikeCount();
                        responseBeanList.get(likePosition).setLikeCount(likeCount + 1);
                        responseBeanList.get(likePosition).setIslike(1);
                        mCommentAdapter.notifyItemRangeChanged(likePosition, 1, mCommentAdapter.GIVELIKE);
                    }
                }
            }
        } else {
            ToastUtils.show(iNetBean.getErrMsg());
        }
    }

    /**
     * 评论成功返回
     */
    @Override
    public void onPostCommentOrReplyAdd(ResponseBody body) {
        try {
            String json = body.string().toString();
            JSONObject object = new JSONObject(json);
            int errCode = object.getInt("ErrCode");
            String respose = object.getString("Response");
            if (errCode == 0) {
                if (comment_id == 0) {//文章评论
                    CommentDetails details = new Gson().fromJson(json, CommentDetails.class);
                    List<CommentDetails.ResponseBean> beanList = details.getResponse();
                    if (beanList != null && !beanList.isEmpty()) {
                        //本地追加评论
                        CommentDetails.ResponseBean bean = beanList.get(0);
                        //原先评论
                        List<CommentDetails.ResponseBean> beans = new ArrayList<>();
                        beans.addAll(mCommentDetails);
                        //显示评论区，隐藏
                        hideEmptyLayout();
                        //清空集合，填充新数据
                        mCommentDetails.clear();
                        mCommentDetails.add(bean);
                        if (!beans.isEmpty()) {
                            mCommentDetails.addAll(beans);
                        }
                        mCommentAdapter.notifyDataSetChanged();
                    }
                    EventBus.getDefault().post(new UpdateCommmentCount(true));
                } else {//评论回复，以及回复的回复
                    List<CommentReplysBean> replysBeans = new Gson().fromJson(respose, new TypeToken<List<CommentReplysBean>>() {
                    }.getType());
                    if (replysBeans != null && !replysBeans.isEmpty()) {
                        //原先的评论回复
                        if (mCommentDetails != null && !mCommentDetails.isEmpty()) {
                            List<CommentReplysBean> list = new ArrayList<>();
                            CommentDetails.ResponseBean bean = mCommentDetails.get(local_position);
                            List<CommentReplysBean> replys = bean.getComment_replys();
                            //重新填充一个集合
                            list.addAll(replys);
                            replys.clear();
                            replys.add(replysBeans.get(0));
                            if (!list.isEmpty()) {
                                //添加以前的数据
                                replys.addAll(list);
                            }
                            //此时，comment_replyCount数量需要增加1
                            int count = bean.getComment_replyCount();
                            count = count + 1;
                            bean.setComment_replyCount(count);
                            mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                        }
                    }
                }
                ToastUtils.show(comment_id == 0 ? "评论成功" : "回复成功");
                //清空输入框
                EventBus.getDefault().post(new CleanKeyBoard());
                //清空标识
                cleanIdentifying();
            } else {
                ToastUtils.show(comment_id == 0 ? "评论失败" : "回复失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClickListener(View view, int position, String contents, String bi_name,
                                    int comment_id, int from_uid) {
        this.local_position = position;
        this.isDeteleReply = false;
        showCopyReplyDeleteDialog(view, contents, bi_name, comment_id, 0, from_uid);
    }

    @Override
    public void onItemChildClickListener(View view, int position, int replyPosition, String
            contents, String bi_name, int comment_id, int reply_id, int reply_user_id) {
        this.local_position = position;
        this.replyPosition = replyPosition;
        this.isDeteleReply = true;
        showCopyReplyDeleteDialog(view, contents, bi_name, comment_id, reply_id, reply_user_id);
    }

    @Override
    public void onItemExpandClickListener(boolean isExpanded, int pageSize,
                                          int comment_id, int local_position) {
        if (isExpanded) {
            this.isDeteleReply = false;
            this.local_position = local_position;
            getPresenter().getOnecommentDetail(comment_id, reply_pageIndex, reply_pageSize);
        }
    }

    @Override
    public void onItemHeaderClickListener(int userid, boolean is_allow_browse_homepage) {
        Intent intent = new Intent();
        if (UserInfoUtils.getUserInfo() == null) {
            LoginUtils.toLogin(getActivity());
        } else if (userid == UserInfoUtils.getUserId()) {
            intent = new Intent(getActivity(), PersonDetailsActivity.class);
            startActivity(intent);
        } else {
            if (!is_allow_browse_homepage) {
                ToastUtils.show("由于对方的设置，你暂时无法浏览他的主页");
                return;
            }
            intent = new Intent(getActivity(), UserHomePageActivity.class);
            intent.putExtra(Constant.USER_ID, userid);
            startActivity(intent);
        }
    }

    @Override
    public void onItemGiveLikeClickListener(int comment_id, int position) {
        this.likePosition = position;
        getPresenter().getCommentlike(articleItem.getContribute_id(), comment_id);
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        BaseActivity activity = (BaseActivity) getActivity();
        return activity.bindToLife();
    }

    /**
     * 复制，回复，删除评论dialog
     */
    private void showCopyReplyDeleteDialog(View view, final String contents, final String bi_name, final int c_id, final int r_id, int from_uid) {
        final EasyPopup mCirclePop = EasyPopup.create()
                .setContentView(getActivity(), R.layout.popupwindow_comment_option)
                .setAnimationStyle(R.style.input_dialog)
                //是否允许点击PopupWindow之外的地方消失
                .setFocusAndOutsideEnable(true)
                .apply();
        TextView deleteTv = mCirclePop.findViewById(R.id.delete);
        View line = mCirclePop.findViewById(R.id.line);
        //当前登录id
        int user_id = UserInfoUtils.getUserId();
        //当前文章的用户id
        int article_user_id = articleItem.getUser_id();
        //如果(1.登录id==文章的用户id,则是自己的文章，可以删除)(2.如果来自from_uid==登录id，可以删除)
        if (user_id == article_user_id || user_id == from_uid) {
            deleteTv.setVisibility(View.VISIBLE);
            line.setVisibility(View.VISIBLE);
        }
        mCirclePop.findViewById(R.id.reply).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserInfoUtils.getUserInfo() == null) {
                    LoginUtils.toLogin(getActivity());
                } else {
                    String replyContent = "回复：" + bi_name;
                    comment_id = c_id;
                    reply_id = r_id;
                    mCirclePop.dismiss();
                    InputCommentDialog inputDialog = getInputDialog();
                    inputDialog.replyComment(replyContent, comment_id, reply_id);
                    inputDialog.show(getChildFragmentManager(), InputCommentDialog.class.getSimpleName());
                }
            }
        });
        mCirclePop.findViewById(R.id.copy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager mCM = (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);
                mCM.setPrimaryClip(ClipData.newPlainText(null, contents));
                ToastUtils.show("复制成功");
                mCirclePop.dismiss();
            }
        });
        deleteTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                comment_id = c_id;
                reply_id = r_id;
                mCirclePop.dismiss();
                deleteCommentDeleteDialog();
            }
        });
        mCirclePop.showAtAnchorView(view, YGravity.ALIGN_TOP, XGravity.CENTER, 0, -100);
    }

    /**
     * 删除该条评论提示
     */
    private void deleteCommentDeleteDialog() {
        BanyanDialog.Builder builder = new BanyanDialog.Builder(getContext());
        builder.setTitle("确认要删除该条评论吗？")
                .setLeft("取消")
                .setRight("确定");
        final BanyanDialog dialog = builder.create();
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                dialog.dismiss();
                getPresenter().getCommentOrReplyDelete(articleItem.getContribute_id(), comment_id, reply_id);
            }
        });
        dialog.show();
    }

    /**
     * 清空标识
     */
    private void cleanIdentifying() {
        comment_id = 0;
        reply_id = 0;
        edtChatInput.setText("");
        if (atMap != null) {
            atMap.clear();
        }
        if (inputCommentDialog != null) {
            inputCommentDialog.cleanIdentifying();
            inputCommentDialog = null;
        }
    }

    /**
     * 显示缺省页面
     */
    protected void showEmptyLayout() {
        if (inflate == null) {
            inflate = viewStub.inflate();
            layoutEmpty = inflate.findViewById(R.id.layout_empty);
            ImageView noDataImg = inflate.findViewById(R.id.no_data_img);
            TextView noDataHint = inflate.findViewById(R.id.no_data_hint);
            noDataImg.setImageResource(R.drawable.empty_comment_bg);
            noDataHint.setText(getString(R.string.comment_empty_hint));
        }
        layoutEmpty.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏缺省页面
     */
    protected void hideEmptyLayout() {
        if (layoutEmpty != null) {
            layoutEmpty.setVisibility(View.GONE);
        }
    }


    /**
     * 一定要销毁dialog，设置为null，防止内存泄漏
     */
    public void dismissDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
        if (inputCommentDialog != null){
            inputCommentDialog.dismissDialog();
        }
    }
}
